import string
import requests
import json
import urllib,re
from bs4 import BeautifulSoup
areaId = "410506"
token= "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2NjQ2OTM2NjksInVzZXJJZCI6IjMwIn0.w-PpLLPzlx0qZuhhldQZ0ahL1y-4qtx8HkfFokxhOZg"
header = {
    "Accept": "application/json, text/plain, */*",
    "token": token,
    "Accept-Encoding": "gzip, deflate, br",
    "Accept-Language": "zh-CN,zh-Hans;q=0.9",
    "Host": "221.13.152.245:5003",
    "Origin": "http://221.13.152.245:5002",
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.6.1 Safari/605.1.15",
    "Referer": "http://221.13.152.245:5002/",
    "device": "admin"
}
def getTargetRecords(str=""):
    try:
        response = requests.post("http://221.13.152.245:5003/appProposal/appproposal/getAllProposalList",json={"title":str,"page":1,"size":300},headers=header)
    except urllib.error.URLError as e:
        # if isinstance(e.reason, socket.timeout):
        print('TIME OUT',e);
    else:
        json1 = json.loads(response.text)["data"]["records"]
        return json1
def checkExist(str,json1=getTargetRecords()):
    if str[0] in "0123456789":
        return len([x for x in json1 if x["serialNumber"] is not None and x["serialNumber"].find(str) != -1]) > 0
    else:
        return len([x for x in json1 if x["title"] is not None and x["title"].find(str) != -1]) > 0
    
def getSourceList():
    try:
        response = requests.post('https://www.zxtaw.com/admin/new_talist_lsh.asp?jc=11|1&tasf=&px=ID%20desc&lb=&tasx=&p=5',headers={"Cookie": "page%5Fn3=; BC=1; BJ=11; admenageid=84; admenagemc=; admenagename=taw; admenagepas=447e9b9e8f69b7fb; admenagepow=; cs=; mymodule=513393; shenfen=%D5%FE%D0%AD%B9%DC%C0%ED%B5%C7%C2%BC; ASPSESSIONIDCESAATBD=PCHFPLMBDMJAGCJMAIHLMEHC"})
        response.encoding ='gb2312'
    except urllib.error.URLError as e:
        # if isinstance(e.reason, socket.timeout):
        print('TIME OUT',e);
    else:
        str1 = response.text
        soup = BeautifulSoup(str1,features="html.parser")
        table = soup.find("table",attrs={"class":"layui-table"})
        return table



def getDetailInfo(url):
    try:
        response = requests.post(url,headers={"Cookie": "page%5Fn3=; BC=1; BJ=11; admenageid=84; admenagemc=; admenagename=taw; admenagepas=447e9b9e8f69b7fb; admenagepow=; cs=; mymodule=513393; shenfen=%D5%FE%D0%AD%B9%DC%C0%ED%B5%C7%C2%BC; ASPSESSIONIDCESAATBD=PCHFPLMBDMJAGCJMAIHLMEHC"})
        response.encoding ='gb2312'
    except urllib.error.URLError as e:
        # if isinstance(e.reason, socket.timeout):
        print('TIME OUT',e);
    else:
        str1 = response.text
        soup = BeautifulSoup(str1,features="html.parser")
        table = soup.find("table",attrs={"class":"layui-table"})
        return table

def getWeiyuanUserInfo(str):
    if len(str) == 0:
        return ""
    try:
        response = requests.get(f"http://221.13.152.245:5003/committee/member/web/list1?name={str}&page=1&size=10",headers={"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2NjQ2OTM2NjksInVzZXJJZCI6IjMwIn0.w-PpLLPzlx0qZuhhldQZ0ahL1y-4qtx8HkfFokxhOZg"})
    except urllib.error.URLError as e:
        # if isinstance(e.reason, socket.timeout):
        print('TIME OUT',e);
    else:
        # print(response.text)
        json1 = json.loads(response.text)["data"]["records"]
        # print(response.text)
        return f"{json1[0]['jiebieName']}-{str}" if len(json1) > 0 else str
    

def getInfoByFields(table):
    # json1=getTargetRecords()
    # pattern = re.compile(r'第([^第号]+)号')
    for x in table.find_all("tr"):
        tds = x.find_all("td")
        # t1 = tds[0].get_text()
        if tds[0].get_text() in ["提案人","案由："]:
            print(tds[1].get_text())
        if tds[0].get_text() == "联名":
            print([getWeiyuanUserInfo(x2.get_text().replace("\n","").replace("\r","").replace("\r","\t").strip()) for x2 in tds[1].children])

def checkGetUnInputDatas(table):
    json1=getTargetRecords()
    pattern = re.compile(r'第([^第号]+)号')
    for x in table.find_all("tr"):
        tds = x.find_all("td")
        t1 = tds[0].get_text()
        if t1[0] in "0123456789" and t1[-1] in "0123456789":
            isInStore = 0
            for item in tds[1].find("b").children:
                if f"{type(item)}" == "<class 'bs4.element.NavigableString'>":
                    number = item.strip()
                    numbers = re.findall(pattern, number)
                    if len(numbers) > 0 and checkExist(numbers[0],json1):
                        isInStore = 1
                elif checkExist(item.get_text(),json1):
                    isInStore = 2
            if isInStore == 0:
                print("--------")
                print(f"https://www.zxtaw.com/admin/{item['href']}")
                getInfoByFields(getDetailInfo(f"https://www.zxtaw.com/admin/{item['href']}"))
                print("\n\n\n\n")


checkGetUnInputDatas(getSourceList())